package com.atguigu.srb.sms.controller.api;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.util.RandomUtils;
import com.atguigu.common.util.RegexValidateUtils;
import com.atguigu.srb.sms.client.CoreUserInfoClient;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.util.SmsProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Doream
 * @Date: 2022/2/3 14:09
 */
@Slf4j
@Api(tags = "短信管理")
//@CrossOrigin
@RestController
@RequestMapping("/api/sms")
public class ApiSmsController {
    @Resource
    SmsService smsService;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    private CoreUserInfoClient coreUserInfoClient;

    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(@ApiParam(value = "手机号码",required = true) @PathVariable("mobile") String mobile){
        // 校验
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);

        Assert.isTrue(!coreUserInfoClient.checkMobile(mobile),ResponseEnum.MOBILE_EXIST_ERROR);

        // 生成验证码
        HashMap<String, Object> map = new HashMap<>();
        String code = RandomUtils.getFourBitRandom();
        map.put("code", code);
        // 将验证码保存到redis数据库
        try {
            redisTemplate.opsForValue().set("srb:sms:code:"+mobile,code,5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("redis服务器异常"+e.getMessage());
        }
        //smsService.send(mobile, SmsProperties.TEMPLATE_CODE,map);

        return R.ok().message("短信发送成功");
    }
}
